<template>
  <div class="exam-monitor">
    <el-card>
      <template #header>
        <div class="main-card-header">
          <span>考试监控</span>
          <el-button @click="handleBack">返回</el-button>
        </div>
      </template>
      <div class="monitor-content">
        <!-- 考试状态卡片 -->
        <el-row :gutter="20" class="status-cards">
          <el-col :span="6">
            <el-card shadow="hover" class="status-card">
              <template #header>
                <div class="card-header">
                  <span>考试状态</span>
                  <el-tag :type="getStatusType(examData.status)">
                    {{ getStatusText(examData.status) }}
                  </el-tag>
                </div>
              </template>
              <div class="status-content">
                <div class="status-item">
                  <span class="label">考试名称：</span>
                  <span class="value">{{ examData.title }}</span>
                </div>
                <div class="status-item">
                  <span class="label">剩余时间：</span>
                  <span class="value countdown">{{ formatTimeLeft }}</span>
                </div>
                <div class="status-item">
                  <span class="label">开始时间：</span>
                  <span class="value">{{ examData.startTime }}</span>
                </div>
                <div class="status-item">
                  <span class="label">结束时间：</span>
                  <span class="value">{{ examData.endTime }}</span>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="status-card">
              <template #header>
                <div class="card-header">
                  <span>考试进度</span>
                  <el-icon><DataLine /></el-icon>
                </div>
              </template>
              <div class="status-content">
                <el-progress
                  type="dashboard"
                  :percentage="statistics.attendanceRate"
                  :color="progressColors"
                >
                  <template #default="{ percentage }">
                    <div class="progress-label">
                      <div class="percentage">{{ percentage }}%</div>
                      <div class="text">已参加</div>
                    </div>
                  </template>
                </el-progress>
                <div class="progress-stats">
                  <div class="stat-item">
                    <span class="label">总人数：</span>
                    <span class="value">{{ statistics.totalStudents }}</span>
                  </div>
                  <div class="stat-item">
                    <span class="label">已参加：</span>
                    <span class="value">{{ statistics.attendedStudents }}</span>
                  </div>
                  <div class="stat-item">
                    <span class="label">未参加：</span>
                    <span class="value">{{ statistics.totalStudents - statistics.attendedStudents }}</span>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="status-card">
              <template #header>
                <div class="card-header">
                  <span>作弊检测</span>
                  <el-icon><Warning /></el-icon>
                </div>
              </template>
              <div class="status-content">
                <div class="cheating-stats">
                  <div class="stat-item">
                    <span class="label">可疑事件：</span>
                    <span class="value warning">{{ cheatingStats.suspiciousEvents }}</span>
                  </div>
                  <div class="stat-item">
                    <span class="label">确认作弊：</span>
                    <span class="value danger">{{ cheatingStats.confirmedCheating }}</span>
                  </div>
                  <div class="stat-item">
                    <span class="label">处理中：</span>
                    <span class="value info">{{ cheatingStats.pendingEvents }}</span>
                  </div>
                </div>
                <el-button
                  type="primary"
                  class="view-events-btn"
                  @click="handleViewAllEvents"
                >
                  查看所有事件
                </el-button>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="status-card">
              <template #header>
                <div class="card-header">
                  <span>实时统计</span>
                  <el-icon><TrendCharts /></el-icon>
                </div>
              </template>
              <div class="status-content">
                <div class="real-time-stats">
                  <div class="stat-item">
                    <span class="label">在线人数：</span>
                    <span class="value">{{ realTimeStats.onlineStudents }}</span>
                  </div>
                  <div class="stat-item">
                    <span class="label">提交人数：</span>
                    <span class="value">{{ realTimeStats.submittedStudents }}</span>
                  </div>
                  <div class="stat-item">
                    <span class="label">平均用时：</span>
                    <span class="value">{{ realTimeStats.averageTime }}分钟</span>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 实时监控区域 -->
        <el-row :gutter="20" class="monitor-section">
          <!-- 作弊事件列表 -->
          <el-col :span="8">
            <el-card class="events-card">
              <template #header>
                <div class="card-header">
                  <span>实时作弊事件</span>
                  <el-button type="primary" link @click="handleRefreshEvents">
                    刷新
                  </el-button>
                </div>
              </template>
              <div class="events-list">
                <el-timeline>
                  <el-timeline-item
                    v-for="event in recentEvents"
                    :key="event.id"
                    :type="getEventTypeTag(event.eventType)"
                    :timestamp="event.time"
                    :hollow="event.status === 'PENDING'"
                  >
                    <div class="event-item">
                      <div class="event-header">
                        <span class="student-name">{{ event.studentName }}</span>
                        <el-tag
                          :type="getEventTypeTag(event.eventType)"
                          size="small"
                        >
                          {{ getEventTypeText(event.eventType) }}
                        </el-tag>
                      </div>
                      <div class="event-content">{{ event.eventData }}</div>
                      <div class="event-actions">
                        <el-button
                          type="primary"
                          link
                          size="small"
                          @click="handleViewEvidence(event)"
                        >
                          查看证据
                        </el-button>
                        <el-button
                          type="success"
                          link
                          size="small"
                          v-if="event.status === 'PENDING'"
                          @click="handleMarkCheating(event)"
                        >
                          标记作弊
                        </el-button>
                        <el-button
                          type="info"
                          link
                          size="small"
                          v-if="event.status === 'PENDING'"
                          @click="handleIgnoreEvent(event)"
                        >
                          忽略
                        </el-button>
                      </div>
                    </div>
                  </el-timeline-item>
                </el-timeline>
              </div>
            </el-card>
          </el-col>

          <!-- 学生实时截图 -->
          <el-col :span="16">
            <el-card class="screenshots-card">
              <template #header>
                <div class="card-header">
                  <span>学生实时截图</span>
                  <div class="header-actions">
                    <el-select
                      v-model="selectedStudent"
                      placeholder="选择学生"
                      class="student-select"
                    >
                      <el-option
                        v-for="student in studentList"
                        :key="student.id"
                        :label="student.name"
                        :value="student.id"
                      />
                    </el-select>
                    <el-button type="primary" @click="handleRefreshScreenshot">
                      刷新截图
                    </el-button>
                  </div>
                </div>
              </template>
              <div class="screenshot-container">
                <div v-if="currentScreenshot" class="screenshot-wrapper">
                  <el-image
                    :src="currentScreenshot.url"
                    fit="contain"
                    :preview-src-list="[currentScreenshot.url]"
                  >
                    <template #error>
                      <div class="screenshot-error">
                        <el-icon><Picture /></el-icon>
                        <span>加载失败</span>
                      </div>
                    </template>
                  </el-image>
                  <div class="screenshot-info">
                    <span class="time">{{ currentScreenshot.time }}</span>
                    <span class="student">{{ currentScreenshot.studentName }}</span>
                  </div>
                </div>
                <div v-else class="screenshot-placeholder">
                  <el-icon><Picture /></el-icon>
                  <span>请选择学生查看实时截图</span>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 证据查看对话框 -->
    <el-dialog
      v-model="evidenceDialogVisible"
      title="作弊证据"
      width="800px"
    >
      <div class="evidence-content">
        <el-tabs v-model="activeEvidenceTab">
          <el-tab-pane label="截图证据" name="screenshots">
            <div class="evidence-screenshots">
              <el-image
                v-for="(img, index) in currentEvidence?.screenshots"
                :key="index"
                :src="img.url"
                :preview-src-list="currentEvidence?.screenshots?.map((s: any) => s.url)"
                fit="cover"
                class="evidence-image"
              />
            </div>
          </el-tab-pane>
          <el-tab-pane label="事件详情" name="details">
            <el-descriptions :column="1" border>
              <el-descriptions-item label="学生姓名">
                {{ currentEvidence?.studentName }}
              </el-descriptions-item>
              <el-descriptions-item label="事件类型">
                {{ getEventTypeText(currentEvidence?.type) }}
              </el-descriptions-item>
              <el-descriptions-item label="发生时间">
                {{ currentEvidence?.timestamp }}
              </el-descriptions-item>
              <el-descriptions-item label="事件描述">
                {{ currentEvidence?.description }}
              </el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>
        </el-tabs>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="evidenceDialogVisible = false">关闭</el-button>
          <el-button
            type="primary"
            @click="handleConfirmCheating(currentEvidence)"
            v-if="currentEvidence?.status === 'PENDING'"
          >
            确认作弊
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { DataLine, Warning, TrendCharts, Picture } from '@element-plus/icons-vue'
import {
  getExamDetail,
  getExamStatistics,
  getCheatingStatistics,
  getRealTimeMonitorData,
  getCheatingEvents,
  getCheatingEvidence,
  getLatestStudentScreenshot,
} from '@/api/exam'
import { getStudents } from '@/api/student'

const router = useRouter()
const route = useRoute()
const examId = Number(route.params.id)

// Data refs
const examData = ref<any>({})
const statistics = ref<any>({
  totalStudents: 0,
  attendedStudents: 0,
  attendanceRate: 0,
  averageScore: 0,
  passRate: 0
})
const cheatingStats = ref<any>({
  suspiciousEvents: 0,
  confirmedCheating: 0,
  pendingEvents: 0
})
const realTimeStats = ref<any>({
  onlineStudents: 0,
  submittedStudents: 0,
  averageTime: 0
})
const recentEvents = ref<any[]>([])
const studentList = ref<any[]>([])
const selectedStudent = ref<number | null>(null)
const currentScreenshot = ref<any>(null)
const evidenceDialogVisible = ref(false)
const currentEvidence = ref<any>(null)
const activeEvidenceTab = ref('screenshots')

// Declare progressColors
const progressColors = [
  { color: '#f56c6c', percentage: 20 },
  { color: '#e6a23c', percentage: 40 },
  { color: '#5cb87a', percentage: 60 },
  { color: '#1989fa', percentage: 80 },
  { color: '#6f7ad3', percentage: 100 }
]

// Countdown timer (optional, based on examData)
const endTime = computed(() => {
  return examData.value.endTime ? new Date(examData.value.endTime).getTime() : 0
})
const timeLeft = ref(0)
const timer = ref<number | null>(null)

const formatTimeLeft = computed(() => {
  if (timeLeft.value <= 0) {
    return '00:00:00'
  }
  const hours = Math.floor(timeLeft.value / (1000 * 60 * 60))
  const minutes = Math.floor((timeLeft.value % (1000 * 60 * 60)) / (1000 * 60))
  const seconds = Math.floor((timeLeft.value % (1000 * 60)) / 1000)
  return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`
})

// Update countdown
const updateCountdown = () => {
  const now = new Date().getTime()
  timeLeft.value = Math.max(0, endTime.value - now)
  if (timeLeft.value > 0) {
    timer.value = setTimeout(updateCountdown, 1000)
  } else {
    clearTimeout(timer.value as number)
  }
}

// Load data functions
const loadExamDetails = async () => {
  try {
    const response = await getExamDetail(examId)
    examData.value = response.data
    updateCountdown() // Start countdown after loading end time
  } catch (error) {
    console.error('获取考试详情失败:', error)
    ElMessage.error('获取考试详情失败')
  }
}

const loadExamStatistics = async () => {
  try {
    const response = await getExamStatistics(examId)
    Object.assign(statistics.value, response.data) // Use Object.assign to update reactive object
  } catch (error) {
    console.error('获取考试统计失败:', error)
    ElMessage.error('获取考试统计失败')
  }
}

const loadCheatingStatistics = async () => {
  try {
    const response = await getCheatingStatistics(examId)
    Object.assign(cheatingStats.value, response.data) // Use Object.assign to update reactive object
  } catch (error) {
    console.error('获取作弊统计失败:', error)
    ElMessage.error('获取作弊统计失败')
  }
}

const loadRealTimeMonitorData = async () => {
  try {
    const response = await getRealTimeMonitorData(examId)
    Object.assign(realTimeStats.value, response.data) // Use Object.assign to update reactive object
  } catch (error) {
    console.error('获取实时监控数据失败:', error)
    ElMessage.error('获取实时监控数据失败')
  }
}

const loadCheatingEvents = async () => {
  try {
    const response = await getCheatingEvents(examId)
    // Assuming response.data is the list of events, adjust if nested (e.g., response.data.list)
    recentEvents.value = response.data.list // Assuming backend returns list in data field
  } catch (error) {
    console.error('获取实时作弊事件失败:', error)
    ElMessage.error('获取实时作弊事件失败')
  }
}

const loadStudentList = async () => {
  try {
    // Assuming getStudents can filter by examId or you need a specific endpoint
    // If no examId filter is available in getStudents, you might need a new API function
    // For now, let's assume a generic getStudents and maybe filter on frontend if necessary,
    // or ideally, the backend provides an endpoint to get students for a specific exam.
    // Let's call a generic getStudents and leave a note if filtering is needed.
    // Or, if getStudentsByExam is added to exam.ts (as planned in last turn):
    // import { getStudentsByExam } from '@/api/exam';
    // const response = await getStudentsByExam(examId);
    // studentList.value = response.data.list; // Adjust based on actual response structure

    // Let's use the generic getStudents from student.ts for now, assuming it fetches all students.
    // TODO: Replace with exam-specific student list API if available.
    const response = await getStudents() // Assuming getStudents from student.ts
    studentList.value = response.data.list // Assuming response structure

  } catch (error) {
    console.error('获取学生列表失败:', error)
    // ElMessage.error('获取学生列表失败'); // Avoid error message for TODO
  }
}

const loadLatestStudentScreenshot = async (studentId: number) => {
  if (!studentId) {
    currentScreenshot.value = null
    return
  }
  try {
    const response = await getLatestStudentScreenshot(examId, studentId)
    currentScreenshot.value = response.data // Assuming response.data is the screenshot object { url, time } or null
  } catch (error) {
    console.error('获取学生截图失败:', error)
    ElMessage.error('获取学生截图失败')
    currentScreenshot.value = null
  }
}

// Handlers
const handleBack = () => {
  router.back()
}

const handleRefreshEvents = () => {
  loadCheatingEvents()
}

const handleViewAllEvents = () => {
  // This button seems to just refresh the list, so call loadCheatingEvents
  loadCheatingEvents()
  // If it was meant to navigate to a separate page for all events, adjust routing here.
}

const handleViewEvidence = async (event: any) => {
  // Assuming event object has an 'id' field for the cheating event ID
  if (!event || event.id === undefined) {
    console.error('Invalid event object for viewing evidence:', event)
    ElMessage.warning('无法查看证据：无效的事件信息')
    return
  }
  try {
    const response = await getCheatingEvidence(examId, event.id)
    currentEvidence.value = response.data // Assuming response.data contains the evidence
    evidenceDialogVisible.value = true
  } catch (error) {
    console.error('获取作弊证据失败:', error)
    ElMessage.error('获取作弊证据失败')
  }
}

const handleMarkCheating = (event: any) => {
  // TODO: Implement API call and logic for marking cheating
  console.warn('TODO: Implement mark cheating API call for event ID:', event.id)
  ElMessage.info('标记作弊功能待实现')
}

const handleIgnoreEvent = (event: any) => {
  // TODO: Implement API call and logic for ignoring event
  console.warn('TODO: Implement ignore event API call for event ID:', event.id)
  ElMessage.info('忽略事件功能待实现')
}

const handleRefreshScreenshot = () => {
  if (selectedStudent.value !== null) {
    loadLatestStudentScreenshot(selectedStudent.value)
  } else {
    ElMessage.warning('请先选择学生')
  }
}

const handleConfirmCheating = (evidence: any) => {
  // TODO: Implement API call and logic for confirming cheating
  console.warn('TODO: Implement confirm cheating API call for evidence:', evidence);
  ElMessage.info('确认作弊功能待实现');
};

// Utility functions (getStatusType, getStatusText, etc.) - keep these as they are local
const getStatusType = (status: string) => {
  const map: Record<string, string> = {
    NOT_STARTED: 'info',
    IN_PROGRESS: 'success',
    ENDED: 'warning'
  }
  return map[status] || 'info'
}

const getStatusText = (status: string) => {
  const map: Record<string, string> = {
    NOT_STARTED: '未开始',
    IN_PROGRESS: '进行中',
    ENDED: '已结束'
  }
  return map[status] || '未知'
}

const getAntiCheatingType = (level: number) => {
  const map: Record<number, string> = {
    0: 'info',
    1: 'success',
    2: 'warning',
    3: 'danger'
  }
  return map[level] || 'info'
}

const getAntiCheatingText = (level: string) => {
  const map: Record<string, string> = {
    NONE: '无',
    LOW: '低',
    MEDIUM: '中',
    HIGH: '高'
  }
  return map[level] || '未知'
}

const getEventTypeTag = (type: string) => {
  const map: Record<string, string> = {
    FACE_MISMATCH: 'warning',
    MULTI_FACE: 'danger',
    SCREEN_SHARING: 'danger',
    // Add other event types if needed
    TAB_SWITCH: 'warning',
    PASTE: 'warning',
    COPY: 'warning',
  }
  return map[type] || 'info'
}

const getEventTypeText = (type: string) => {
  const map: Record<string, string> = {
    FACE_MISMATCH: '人脸不匹配',
    MULTI_FACE: '多人脸',
    SCREEN_SHARING: '屏幕共享',
    // Add other event types if needed
    TAB_SWITCH: '切屏',
    PASTE: '粘贴',
    COPY: '复制',
  }
  return map[type] || '未知事件'
}

// On component mount
onMounted(() => {
  loadExamDetails()
  loadExamStatistics()
  loadCheatingStatistics()
  loadRealTimeMonitorData()
  loadCheatingEvents()
  loadStudentList() // Load student list on mount
})

// Clean up timer on unmount
onUnmounted(() => {
  if (timer.value !== null) {
    clearTimeout(timer.value)
  }
})

// Watch for selectedStudent changes to load screenshot
// Removed the watch as it was not in the initial code, rely on explicit refresh for now.
// If real-time screenshot updates are needed, a more complex approach (websockets?) would be required.
</script>

<style scoped>
.exam-monitor {
  padding: 20px;
  box-sizing: border-box;
}

.main-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.monitor-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.status-cards {
  margin-bottom: 20px;
}
.status-card {
  height: 100%;
}

:deep(.el-card) {
  display: flex;
  flex-direction: column;
}

:deep(.el-card__body) {
  flex: unset;
  overflow: unset;
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.status-item {
  margin-bottom: 10px;
  display: flex;
  justify-content: space-between;
}

.status-item .label {
  color: #666;
}

.status-item .value {
  font-weight: bold;
}

.status-item .countdown {
  color: #f56c6c;
}

.progress-label {
  text-align: center;
}

.progress-label .percentage {
  font-size: 20px;
  font-weight: bold;
  color: #409EFF;
}

.progress-label .text {
  font-size: 14px;
  color: #666;
}

.progress-stats,
.cheating-stats,
.real-time-stats {
  margin-top: 20px;
}

.stat-item {
  margin-bottom: 10px;
  display: flex;
  justify-content: space-between;
}

.stat-item .label {
  color: #666;
}

.stat-item .value {
  font-weight: bold;
}

.stat-item .value.warning {
  color: #e6a23c;
}

.stat-item .value.danger {
  color: #f56c6c;
}

.stat-item .value.info {
  color: #909399;
}

.view-events-btn {
  width: 100%;
  margin-top: 10px;
}

.monitor-section {
  margin-top: 20px;
  min-height: 0;
  flex: 1;
  display: flex;
}

.events-card,
.screenshots-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  min-height: 0;
}
.events-list {
  flex: 1;
  min-height: 0;
  overflow-y: auto;
}

.event-item {
  padding: 5px 0;
}

.event-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 5px;
}

.student-name {
  font-weight: bold;
}

.event-content {
  color: #666;
  margin-bottom: 5px;
}

.event-actions {
  display: flex;
  gap: 10px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.student-select {
  width: 200px;
}

.screenshot-container {
  flex: 1;
  min-height: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
  border-radius: 4px;
  overflow: auto;
}

.screenshot-wrapper {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.screenshot-info {
  position: absolute;
  bottom: 10px;
  left: 10px;
  background-color: rgba(0, 0, 0, 0.6);
  color: white;
  padding: 5px 10px;
  border-radius: 4px;
  display: flex;
  gap: 10px;
}

.screenshot-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #909399;
}

.screenshot-placeholder .el-icon {
  font-size: 48px;
  margin-bottom: 10px;
}

.screenshot-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #909399;
}

.screenshot-error .el-icon {
  font-size: 48px;
  margin-bottom: 10px;
}

.evidence-content {
  min-height: 400px;
}

.evidence-screenshots {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 10px;
  padding: 10px;
}

.evidence-image {
  width: 100%;
  height: 150px;
  border-radius: 4px;
  cursor: pointer;
}

:deep(.el-timeline-item__node) {
  background-color: var(--el-color-primary);
}

:deep(.el-timeline-item__node.is-hollow) {
  background-color: transparent;
  border-color: var(--el-color-primary);
}

:deep(.el-select),
:deep(.el-form-item__content) {
  min-width: 200px;
}
:deep(.el-select-dropdown) {
  min-width: 220px !important;
}
:deep(.el-select-dropdown__item) {
  white-space: normal;
  word-break: break-all;
  min-width: 200px;
}
</style>
 